<script lang="tsx" setup>
import { ref, useAttrs } from 'vue';
import { useDictStore } from '@/store/modules/dict';

const dictStore = useDictStore();
const attrs = useAttrs();
interface Props {
  // 字典编码
  dictCode: string;
  // 控件类型
  selectType: 'select' | 'radio' | 'checkbox';
  selectOptions?: any[];
}

interface Emits {
  (event: 'change', value: any): void;
}

const emit = defineEmits<Emits>();
const value: any = defineModel('value', { required: true, type: [Array, String, null] });

const props = defineProps<Props>();
const selectRef = ref(null);
const radioRef = ref(null);
const checkboxRef = ref(null);

const options = ref<any[]>([]);
async function getSelectOptions() {
  options.value = await dictStore.getDict(props.dictCode);
}

if (!props?.selectOptions?.length) {
  getSelectOptions();
} else {
  options.value = props.selectOptions;
}

function getRef() {
  if (props.selectType === 'select') {
    return selectRef.value;
  }
  if (props.selectType === 'radio') {
    return radioRef.value;
  }
  if (props.selectType === 'checkbox') {
    return checkboxRef.value;
  }
  return null;
}

function change(val: any) {
  emit('change', val);
}

defineExpose({
  getRef
});
</script>

<template>
  <template v-if="props.selectType === 'select'">
    <ASelect
      v-bind="attrs"
      ref="selectRef"
      v-model:value="value"
      :options="options"
      class="min-form-control"
      @change="change"
    ></ASelect>
  </template>
  <template v-else-if="props.selectType === 'radio'">
    <ARadioGroup v-bind="attrs" ref="radioRef" v-model:value="value" :options="options" @change="change">
      <ARadio v-for="(item, index) in options" :key="index" :value="item.value" :disabled="item.disabled">
        {{ item.label }}
      </ARadio>
    </ARadioGroup>
  </template>
  <template v-else-if="props.selectType === 'checkbox'">
    <template v-if="attrs.useGrid">
      <ACheckboxGroup v-bind="attrs" ref="checkboxRef" v-model:value="value" class="w-full" @change="change">
        <ARow>
          <ACol v-for="(item, index) in options" :key="index" :span="item.span || 6">
            <ACheckbox :value="item.value">{{ item.label }}</ACheckbox>
          </ACol>
        </ARow>
      </ACheckboxGroup>
    </template>
    <template v-else>
      <ACheckboxGroup
        v-bind="attrs"
        ref="checkboxRef"
        v-model:value="value"
        :options="options"
        @change="change"
      ></ACheckboxGroup>
    </template>
  </template>
</template>
